<template>
  <div id="productSpec">
    <div style="margin: 5px; padding: 5px;">
      <el-button type="success" round @click="showAdd">+ 添加</el-button>
    </div>
    <el-input
      v-model="pages.searchName"
      placeholder="请输入规格名称"
      style="width: 200px; margin: 5px"
    />
    <el-button @click="fetchPages">搜索</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="规格名称" prop="specName" />
      <el-table-column label="规格值">
        <template #default="scope">
          <div
            v-for="(item1, index1) in scope.row.specValue"
            :key="index1"
            style="padding: 5px; margin: 0;width: 100%;"
          >
            {{ item1.key }}:
            <span
              v-for="(item2, index2) in item1.valueList"
              :key="index2"
              class="div-atrr"
            >
              {{ item2 }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="editShow(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页页码-->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pages.pageNum"
        v-model:page-size="pages.pageSize"
        :pages-sizes="[2, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pages.total"
        @size-change="fetchPages"
        @current-change="fetchPages"
      />
    </div>

    <!--添加\修改用户表单对话框-->
    <el-dialog v-model="dialogVisible" :title="action" width="40%">
      <el-form label-width="120px">
        <el-form-item label="规格名称">
          <el-input v-model="productSpec.specName" />
        </el-form-item>
        <el-form-item>
          <el-button size="default" type="success" @click="addSpec">
            添加新规格
          </el-button>
        </el-form-item>
        <el-form-item
          label=""
          v-for="(item, index) in productSpec.specValue"
          :key="index"
        >
          <el-row>
            <el-col :span="10">
              <el-input
                v-model="item.key"
                placeholder="规格"
                style="width: 90%;"
              />
            </el-col>
            <el-col :span="10">
              <el-input
                v-model="item.valueList"
                placeholder="规格值(如:白色,红色)"
                style="width: 90%;"
              />
            </el-col>
            <el-col :span="4">
              <el-button
                size="default"
                type="danger"
                @click="deleteSpec(index)"
              >
                删除
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item align="right" #default="scope">
          <div v-if="productSpec.id">
            <el-button type="primary" @click="updateSpec">
              提交
            </el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="addProductSpec">提交</el-button>
          </div>
          <el-button @click="updateEsc">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  findPage,
  doAdd,
  updateProductSpec,
  deleteProductSpec,
} from '@/api/productSpec'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const dialogVisible = ref(false)
const pages = reactive({
  pageNum: 1,
  pageSize: 4,
  searchName: '',
  total: 0,
})

// 分页查询
onMounted(() => {
  fetchPages()
})
const fetchPages = async () => {
  const res = await findPage(pages.pageNum, pages.pageSize, pages.searchName)
  pages.total = res.data.total
  tableData.value = res.data.records
  // 将规格字符串转换成规格js对象
  tableData.value.forEach(item => {
    item.specValue = JSON.parse(item.specValue)
  })
}

// 添加
const productSpec = reactive({
  id: '',
  specName: '',
  specValue: [
    {
      key: '颜色',
      valueList: ['白色', '红色', '黑色'],
    },
    {
      key: '内存',
      valueList: ['8G', '18G'],
    },
  ],
})
const action = ref('添加或修改')
// 展示添加弹窗
const showAdd = () => {
  productSpec.id = ''
  productSpec.specName = ''
  productSpec.specValue = []
  action.value = '添加'
  dialogVisible.value = true
}

// 点击添加新规格后增加输入框
const addSpec = () => {
  productSpec.specValue.push({})
}
// 删除输入框
const deleteSpec = index => {
  productSpec.specValue.splice(index, 1)
}
// 添加商品规格
const addProductSpec = async () => {
  // 其实就是深拷贝
  const productSpecClone = JSON.parse(JSON.stringify(productSpec))
  // 将productSpecClone.specValue.valueList转换成数组，因为后端需要的数组格式的数据[{"key":"内存","valueList":["8G","18G","32G"]}]
  // v-model绑定的数据模型为字符串
  //TODO 2025/1/8 这段到底要不要  这一段是吧字符串合并，例如 属性1：123   ， 如果不加这段会变成 1，2，3
  productSpecClone.specValue.forEach(item => {
    item.valueList = item.valueList.split(',')
  })
  productSpecClone.specValue = JSON.stringify(productSpecClone.specValue)
  const res = await doAdd(productSpecClone)
  if (res.code === 200) {
    ElMessage.success('添加成功')
  } else ElMessage.error(res.message)
  dialogVisible.value = false
  fetchPages()
}

// 删除
const handleDelete = id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ref = await deleteProductSpec(id)
      if (ref.code === 200) {
        ElMessage.success('删除成功')
      } else ElMessage.error(ref.message)
      await fetchPages()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

// 编辑页面显示
const editShow = row => {
  action.value = '编辑'
  productSpec.id = row.id
  productSpec.specName = row.specName
  productSpec.specValue = row.specValue
  dialogVisible.value = true
}

// 提交编辑
const updateSpec = async () => {
  // 需要将productSpec.value.specValue转换成json字符串提交到后端，通过clone一个新的对象进行实现
  const productSpecClone = JSON.parse(JSON.stringify(productSpec))
  // 将productSpecClone.specValue.valueList转换成数组，因为后端需要的数组格式的数据[{"key":"内存","valueList":["8G","18G","32G"]}]
  // v-model绑定的数据模型为字符串
  productSpecClone.specValue.forEach(item => {
    if (typeof item.valueList === 'string') {
      // 针对规格数据修改完毕以后数据类型有可能会变成string，针对string类型的数据将其转换成数组
      item.valueList = item.valueList.split(',')
    }
  })
  productSpecClone.specValue = JSON.stringify(productSpecClone.specValue)
  const res = await updateProductSpec(productSpecClone)
  if (res.code === 200) {
    ElMessage.success('修改成功')
  } else ElMessage.error(res.message)
  dialogVisible.value = false
  fetchPages()
}

// 修改取消
const updateEsc = () => {
  dialogVisible.value = false
  fetchPages()
}
</script>

<style scoped>
#productSpec .div-atrr {
  padding: 3px 7px;
  margin: 1px;
  background-color: powderblue;
  border-radius: 5px;
}
</style>
